function formatNumber (n) {
    const str = n.toString()
    return str[1] ? str : `0${str}`
}

export function formatTime (date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()

    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    const t1 = [year, month, day].map(formatNumber).join('/')
    const t2 = [hour, minute, second].map(formatNumber).join(':')

    return `${t1} ${t2}`
}

export function debounce (func, delay) {
    let timer
    return function (...args) {
        if (timer) {
            window.clearTimeout(timer)
        }
        timer = window.setTimeout(() => {
            func.apply(this, args)
        }, delay)
    }
}

function formatType (type, format, value, attributes) {
    const regExpMap = {
        year: '(Y+)',
        month: '(M+)',
        date: '(D+)',
        hour: '(h+)',
        minute: '(m+)',
        second: '(s+)',
        quarter: '(q+)',
        millisecond: '(S)'
    }

    if (new RegExp(regExpMap[type], attributes).test(format)) {
        const replaceStr = type === 'year'
            ? value.toString().substr(4 - RegExp.$1.length)
            : (RegExp.$1.length === 1) ? value : pad(value)
        format = format.replace(RegExp.$1, replaceStr)
    }

    return format
}

function pad (value) {
    return ('00' + value).substr(('' + value).length)
}

export function formatDate (date, format) {
    const map = {
        year: date.getFullYear(),
        month: date.getMonth() + 1,
        date: date.getDate(),
        hour: date.getHours(),
        minute: date.getMinutes(),
        second: date.getSeconds(),
        quarter: Math.floor((date.getMonth() + 3) / 3),
        millisecond: date.getMilliseconds()
    }

    for (const key in map) {
        format = formatType(key, format, map[key])
    }

    return format
}

